//index.js  
//获取应用实例 
const app = getApp();
const { $Toast } = require('../../dist/base/index');
const { $Message } = require('../../dist/base/index');
Page({
  data: {
    lianjieshow: true,
    buttonshow: false,
    yundongshow: false,
    xueyashow: false,
    xinlvshow: false,
    xueyangshow: false,
    devices: "", //可以连接的设备
    connectedDeviceId: "", //已连接设备uuid  
    services: "", // 连接设备的服务  
    servicesId: "", //操作的service
    writeCharacteristicsId: "", //可写特征值uuid  
    readCharacteristicsId: "", //可读特征值uuid  
    wirtecharacteristicsId: '',
    dianliang: '',
    dingshixinlv: '',
    totalSteps: '',
    calorie: '',
    distance: '',
    duration: '',
    recTimeData: [],
    szyData: [],
    ssyData: [],
    totalData: [],
    xinlvData: [],
    xueyangData: [],
    actions5: [
      {
        name: '取消'
      },
      {
        name: '校正时间',
        color: '#ed3f14',
        loading: false
      }
    ],
    visible5: false,
  },

  onLoad: function () {
    // this.analysisData();
    if (wx.openBluetoothAdapter) {
      wx.openBluetoothAdapter()
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示  
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //开始连接  
  lanya1: function () {
    var that = this;
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.showLoading({
          title: '开启蓝牙适配器',
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        //搜索设备
        wx.startBluetoothDevicesDiscovery({
          services: ['FEE7'],
          allowDuplicatesKey: false,
          success: function (res) {
            console.info('开启搜索周边设备');
            console.info('开启搜索周边设备', res);
            wx.hideLoading();
            wx.showLoading({
              title: '开启搜索周边设备',
            })
            //显示可以连接的设备
            wx.getBluetoothDevices({
              success: function (res) {
                wx.hideLoading();
                if (res.devices == "") {
                  wx.showToast({
                    title: '没有设备,请重试',
                  })
                }
                console.info("可以连接的设备", res.devices);
                //是否有已连接设备  
                wx.getConnectedBluetoothDevices({
                  success: function (res) {
                    that.setData({
                      connectedDeviceId: res.deviceId,
                    })

                  }

                })
                that.setData({
                  devices: res.devices
                })
              }
            })
          }
        })
      },
      fail: function () {
        wx.showToast({
          title: '请开启蓝牙设备',
        })
        // this.lan1();
        this.lanya0();

      }
    })
  },

  //连接设备  
  connectTO: function (e) {
    //先停止搜索
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("停止搜索设备");
      }
    })
    var that = this;
    wx.createBLEConnection({
      deviceId: e.currentTarget.id,
      success: function (res) {
        that.setData({
          connectedDeviceId: e.currentTarget.id
        }),
          wx.getBLEDeviceServices({
            deviceId: that.data.connectedDeviceId,
            success: function (res) {
              that.setData({
                services: res.services,
                servicesId: res.services[0].uuid
              })
              console.info("获取服务的uuid", that.data.servicesId);
              wx.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
                deviceId: that.data.connectedDeviceId,
                // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
                serviceId: that.data.servicesId,
                success: function (res) {
                  console.info("characteristics属性值", res.characteristics);
                  that.setData({
                    readCharacteristicsId: res.characteristics[0].uuid,
                    wirtecharacteristicsId: res.characteristics[1].uuid
                  }),
                    wx.notifyBLECharacteristicValueChange({
                      deviceId: that.data.connectedDeviceId,
                      serviceId: that.data.servicesId,
                      characteristicId: that.data.readCharacteristicsId,
                      state: true,
                      success: function (res) {
                        console.info('start notify');
                        that.setData({
                          lianjieshow: false,
                          buttonshow: true
                        });
                        wx.vibrateShort({
                          success: function (res) {
                            wx.showToast({
                              title: '连接成功',
                              icon: 'success',
                              duration: 2000
                            })
                          }
                        })

                      }
                    });
                },
                fail: function () {
                  console.log("fail");
                },
                complete: function () {
                  console.log("complete");
                }
              })
            },
          })

      },
      fail: function () {
        console.log("调用失败");
        // that.lanya5();
      },
      complete: function () {
        // that.lanya5();
      }

    })
    console.log(that.data.connectedDeviceId);
  },

  getDataByType: function (event) {
    $Toast({
      content: '数据为车上采集',
      type: 'warning'
    });
    var that = this;
    var type = event.currentTarget.dataset.type;
    var data = {
      staffId: app.globalData.staffId,
      type: type
    }
    var url = 'dataUploadBySearch';
    that.sendData(data, url);

  },

  getshoudongxueya: function () {
    var that = this;
    wx.onBLECharacteristicValueChange(function (res) {
      console.info('获取手动血压', res.value);
      console.log(that.ab2hex(res.value));

      var data = {
        macId: "1",
        tpDatas: that.ab2hex(res.value),
        staffId: app.globalData.staffId
      }
      var url = 'dataUpload';
      that.sendData(data, url);

    });
    setTimeout(function () {
      console.log("----timeOut----");
      that.fasongshoudongxueya();
    }, 1100);
  },

  getyundong: function () {
    var that = this;
    wx.onBLECharacteristicValueChange(function (res) {
      console.info('获取运动', res.value);
      console.log(that.ab2hex(res.value));
      var data = {
        macId: "1",
        tpDatas: that.ab2hex(res.value),
        staffId: app.globalData.staffId
      }
      var url = 'dataUpload';
      that.sendData(data, url);
    });
    setTimeout(function () {
      console.log("----timeOut----");
      that.fasongyundong();
    }, 1100);
  },

  setDate: function () {
    var that = this;
    wx.onBLECharacteristicValueChange(function (res) {
      console.info('设置时间', res.value);
      console.log(that.ab2hex(res.value));
      that.setData({
        visible5: false,
      });
      $Message({
        content: '设置成功',
        type: 'success'
      });
    });
    setTimeout(function () {
      console.log("----timeOut----");
      that.faDate();
    }, 1100);

  },

  //获取定时心率数据
  getdingshixinlv: function () {
    var that = this;
    wx.onBLECharacteristicValueChange(function (res) {
      console.info('获取定时心率', res.value);
      console.log(that.ab2hex(res.value));
    });
    setTimeout(function () {
      console.log("----timeOut----");
      that.fasongdingshixinl();
    }, 1100);
  },

  faDate: function () {
    console.info("开始操作校验时间");
    var that = this;
    let buffer = new ArrayBuffer(16);
    let dataView = new DataView(buffer);
    var time = that.toDateTime();
    var index = 1;
    var date = new Date();
    var year = date.getFullYear();
    var years = parseInt((year - 2000), 16);
    var month = parseInt((date.getMonth() + 1), 16);
    var day = parseInt(date.getDate(), 16);
    var hour = parseInt(date.getHours(), 16);
    var minute = parseInt(date.getMinutes(), 16);
    var second = parseInt(date.getSeconds(), 16);

    dataView.setUint8(0, index);
    dataView.setUint8(1, years);
    dataView.setUint8(2, month);
    dataView.setUint8(3, day);
    dataView.setUint8(4, hour);
    dataView.setUint8(5, minute);
    dataView.setUint8(6, second);
    dataView.setUint8(7, 0);
    console.info(years, month, day, hour, minute, second);
    var end = index + years + month + day + hour + minute + second;
    dataView.setUint8(15, end);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.servicesId,
      characteristicId: that.data.wirtecharacteristicsId,
      value: buffer,
      success: function (res) {
        $Message({
          content: '校验时间成功',
          type: 'success',
          duration: 2
        });
      },
      fail: function (res) {
        $Message({
          content: '校验时间失败',
          duration: 2
        });
      }
    });

  },
  //发送手动血压的数据
  fasongshoudongxueya: function () {
    console.info("开始操作发送手动血压数据开始");
    var that = this;
    let buffer = new ArrayBuffer(16);
    let dataView = new DataView(buffer);
    var time = that.toDateTime();
    var index = 20;
    dataView.setUint8(0, index);
    dataView.setUint8(5, 1);
    dataView.setUint8(6, 2);
    var end = index + 1 + 2;
    dataView.setUint8(15, end);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.servicesId,
      characteristicId: that.data.wirtecharacteristicsId,
      value: buffer,
      success: function (res) {
        console.info('发送手动血压成功', res);
      },
      fail: function (res) {
        wx.showToast({
          title: '获取数据失败',
        })
        console.info('发送手动血压失败', res);
      }
    });
  },
  //start 4.13	定时血压数据获取
  fasongdingshixueya: function () {
    console.info("开始操作发送dingshi血压数据开始");
    var that = this;
    let buffer = new ArrayBuffer(16);
    let dataView = new DataView(buffer);
    var time = that.toDateTime();
    var index = 13;
    dataView.setUint8(0, index);
    dataView.setUint8(5, 1);
    dataView.setUint8(6, 100);
    var end = index + 1 + 2;
    dataView.setUint8(15, end);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.servicesId,
      characteristicId: that.data.wirtecharacteristicsId,
      value: buffer,
      success: function (res) {
        console.info('发送dingshi血压成功', res);
      },
      fail: function (res) {
        console.info('发送dingshi血压失败', res);
      }
    });

  },

  fasongyundong: function () {
    console.info("开始操作发送运动数据开始");
    var that = this;
    let buffer = new ArrayBuffer(16);
    let dataView = new DataView(buffer);
    var time = that.toDateTime();
    var index = 7;
    dataView.setUint8(0, index);
    dataView.setUint8(15, index);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.servicesId,
      characteristicId: that.data.wirtecharacteristicsId,
      value: buffer,
      success: function (res) {
        console.info('发送运动成功', res);
      },
      fail: function (res) {
        console.info('发送运动失败', res);
      }
    });
  },
  fasongdingshixinl: function () {
    console.info("开始操作发送定时心率数据开始");
    var that = this;
    let buffer = new ArrayBuffer(16);
    let dataView = new DataView(buffer);
    var time = that.toDateTime();
    console.info("时间为====", time);
    var index = 21;
    var time1 = time.slice(0, 2);
    var time2 = time.slice(2, 4);
    var time3 = time.slice(4, 6);
    var time4 = time.slice(6, 8);
    var end = parseInt(index) + parseInt(time1) + parseInt(time2) + parseInt(time3) + parseInt(time4);
    console.info("时间为1====", time1);
    console.info("时间为2====", time2);
    console.info("时间为3====", time3);
    console.info("时间为4====", time4);
    console.info("时间为end====", end);
    dataView.setUint8(0, index);
    dataView.setUint8(1, time1, true);
    dataView.setUint8(2, time2, true);
    dataView.setUint8(3, time3, true);
    dataView.setUint8(4, time4, true);
    dataView.setUint8(15, end);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: that.data.servicesId,
      characteristicId: that.data.wirtecharacteristicsId,
      value: buffer,
      success: function (res) {
        console.info('发送定时心率成功', res);
      },
      fail: function (res) {
        console.info('发送定时心率失败', res);
      }
    });

  },

  //断开设备连接  
  lanya0: function () {
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        that.setData({
          connectedDeviceId: "",
        })
      }
    })
  },
  toDateTime: function () {
    var date2 = new Date('2018-09-04');
    var time1 = date2.getTime();
    var time2 = time1 + "";
    return time2;
  },

  ab2hex: function (buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },

  sendData: function (data, url) {
    var that = this;
    that.setData({
      totalData: []
    })
    app.func.req(data, url, function (res) {

      console.info("上传数据返回结果", res);
      var dataType = res.data.dataType;
      var searchType = res.data.type;
      console.info(searchType)
      if (res.data.code == "0") {
        console.info("拿到的数据为", res.data.data);
        if (dataType === 'yundong') {
          that.setData({
            yundongshow: true,
            xueyashow: false,
            xueyangshow: false,
            xinlvshow: false,
            totalSteps: res.data.data.totalSteps,
            calorie: res.data.data.calorie,
            distance: res.data.data.distance,
            duration: res.data.data.duration,
          });
        } else if (dataType == 'zhidingxueya') {
          console.info("recTime", res.data.data.recTime);
          let totalData = that.data.totalData;
          let arrStr = { recTime: res.data.data.recTime, szy: res.data.data.szy, ssy: res.data.data.ssy };
          totalData.push(arrStr);
          totalData.sort(function (a, b) {
            return Date.parse(b.recTime.replace(/-/g, "/")) - Date.parse(a.recTime.replace(/-/g, "/"));
          });
          // let recTimeData = that.data.recTimeData;
          // recTimeData.push(res.data.data.recTime.slice(8,10));

          // let szyData = that.data.szyData;
          // szyData.push(res.data.data.szy);

          // let ssyData = that.data.ssyData;
          // ssyData.push(res.data.data.ssy);
          that.setData({
            xueyashow: true,
            xueyangshow: false,
            yundongshow: false,
            xinlvshow: false,
            totalData: totalData
          });
          if (totalData == "") {
            $Message({
              content: '未查询到数据',
              type: 'warning'
            });
          }
          console.info("totalData", totalData);
        }
        if (searchType == 'xinlv') {
          let xinlvData = res.data.data;
          console.info("xinlvData", xinlvData);
          if (xinlvData == "") {
            $Message({
              content: '未查询到数据',
              type: 'warning'
            });
          }
          that.setData({
            yundongshow: false,
            xueyashow: false,
            xinlvshow: true,
            xueyangshow: false,
            xinlvData: xinlvData
          });
        }
        else if (searchType == 'xueyang') {
          let xueyangData = res.data.data;
          console.info("xueyang", xueyangData);
          if (xueyangData == "") {
            $Message({
              content: '未查询到数据',
              type: 'warning'
            });
          }
          that.setData({
            yundongshow: false,
            xueyashow: false,
            xueyangshow: true,
            xinlvshow: false,
            xueyangData: xueyangData
          });


        }

      } else {
        wx.showToast({
          title: "解析失败"
        })
        wx.hideLoading();
      }
    });
  },
  searchXueya: function () {
    app.globalData.recTimeData = this.data.recTimeData;
    app.globalData.szyData = this.data.szyData;
    app.globalData.ssyData = this.data.ssyData;
    wx.navigateTo({
      url: '../line/line',
    })
  }

})